package org.example.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.example.mapper.UserMapper;
import org.example.pojo.*;
import org.example.service.RoleService;
import org.example.service.UserService;
import org.example.util.JWTUtils;

import org.example.util.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
@Api(tags = "User测试")
public class UserController {


    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserMapper userMapper;




    public HttpServletRequest request;


    @GetMapping("/showUsers")
    @ResponseBody
    @ApiOperation("显示全部管理员")
    public ResponseData showUsers(int page,int limit){

        //使用PageHelper开启分页功能
        PageHelper.startPage(page,limit);

        //紧跟着PageHelper.startPage(page,limit)的下一条查询语句会被拦截
        //添加分页实现,并且查询了此sql对应的count
        List<User> users =  userService.selectUsers();

        //根据查询出来的集合生成一个PageInfo对象
        PageInfo<User> userPageInfo = new PageInfo<>(users);


        ResponseData jsonData = ResponseData.getJsonData(users,(int)userPageInfo.getTotal());

        return jsonData;


    }

    @PostMapping("/login")
    @ResponseBody
    @ApiOperation("登录")
    public ResponseData login(@RequestBody  User user){

        User user1 =new User();
        try {
           user1 =  userService.selectUserByNameAndPwd(user);
            if(user1!=null & user1.getmLogin().equals("1") &user1.getmStatus().equals("1")){

                String rName = user1.getrName();
                User userId = userMapper.selectUserByNo(user.getmNo());

                Map<String,String> map = new HashMap<>();
                map.put("mName",user1.getmName());
                map.put("mNo",user1.getmNo());
                //登录成功
                //生成JWT 令牌
                String token =  JWTUtils.getToken(map);
                return  ResponseData.allResponse(getRes(userId.getmId()),token,100,1);
            }

        }catch (Exception e){
            return ResponseData.error("账号密码错误或账号被冻结",101);
        }







        return ResponseData.error("登录错误",101);
    }

    @PostMapping("/editUser")
    @ResponseBody
    @ApiOperation("编辑管理员")
    public ResponseData edit(@RequestBody UserPwd userPwd){


//        String token = request.getHeader("token");
//        token = request.getParameter("token");

        String userNo = userPwd.getmNo();

        User user =  userService.selectUserByNo(userNo);
        String oldPwd = user.getmPassword();



        if (userPwd.getmPassword().equals(oldPwd)){
            if (userPwd.getmNewPassword().equals(userPwd.getmNewPassword2())){

                user.setmName(userPwd.getmName());
                user.setmPassword(userPwd.getmNewPassword());
                user.setmSex(userPwd.getmSex());
                user.setmEmail(userPwd.getmEmail());
                user.setmPhone(userPwd.getmPhone());
                int n = userService.updateUserPwd(user);
                return ResponseData.getSccesss("修改成功",100);
            }else {
                return ResponseData.getSccesss("2次密码不一致",102);
            }
        }else {
            return ResponseData.getSccesss("旧密码错误",100);
        }


    }

    public List<ResPojo> getRes(int rId){



        ResRolePojo resids = roleService.selectResRolePojo(rId);


        List<ResPojo> resources = new ArrayList<>();
        for (int id:resids.getRoleRes()) {


            ResPojo resource = roleService.getParRes(id);


            List<ResPojo> resourcesChilds = roleService.showChildResouce(resource.getResId());
            resource.setChilds(resourcesChilds);


            System.out.println(resource);
            resources.add(resource);


        }


        return  resources;

    }

    @GetMapping("/selectByAll/{page}/{limit}/{var}")
    @ResponseBody
    @ApiOperation("模糊查询变量")
    public ResponseData selectByAll(@ApiParam("当前页") @PathVariable int page, @ApiParam("每一页显示几条数据") @PathVariable int limit, @ApiParam("模糊查询输入的内容") @PathVariable String var) {


        PageHelper.startPage(page,limit);


        Map<String,String> map = new HashMap<>();

        List<User> users = userService.selectVariablesByAll(var);
        //根据查询出来的集合生成一个PageInfo对象
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        ResponseData responseData = ResponseData.getJsonData(users,(int)userPageInfo.getTotal());
        return responseData;

    }

    @PostMapping("/addUser")
    @ResponseBody
    @ApiOperation("添加管理员")
    public ResponseData addUser(@RequestBody User user){



        int rId = roleService.selectByName(user.getrName()).getrId();

        AddUser addUser = new AddUser();
        addUser.setmEmail(user.getmEmail());
        addUser.setmName(user.getmName());
        addUser.setmPassword(user.getmPassword());
        addUser.setmNo(user.getmNo());
        addUser.setmPhone(user.getmPhone());
        addUser.setmSex(user.getmSex());
        addUser.setrName(rId);

        userService.addRole(addUser);

        return ResponseData.getSccesss("添加成功",100);

    }


    @PostMapping("/deleteUser")
    @ResponseBody
    @ApiOperation("删除管理员")
    public ResponseData deleteUser(Integer mId){




        userService.deleteUser(mId);


        return ResponseData.getSccesss("删除成功",100);

    }

    @PostMapping("/status")
    @ResponseBody
    @ApiOperation("修改使用状态")
    public ResponseData status(int mId){

        User user =  userService.selectUserById(mId);


        if(user.getmStatus().equals("0")){
            user.setmStatus("1");
        }else {
            user.setmStatus("0");
        }
        userMapper.updateStaus(user);



        return ResponseData.getSccesss("修改成功",100);

    }

    @PostMapping("/loginStatus")
    @ResponseBody
    @ApiOperation("修改登录状态")
    public ResponseData loginStatus(int mId){

        User user =  userService.selectUserById(mId);

        System.out.println(user.getmLogin().equals("0"));
        if(user.getmLogin().equals("0")){
            user.setmLogin("1");
        }else {
            user.setmLogin("0");
        }
        userMapper.updateLogin(user);



        return ResponseData.getSccesss("修改成功",100);

    }

}
